package com.wx_shop.web.houtai.utiltools;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;



@Component
public class UploadFile {



    public static JSONObject UploadFile(MultiValueMap<String, MultipartFile> filemap, String Path){

        MultipartFile upfile = null;

        //文件扩展名
        String Exname = "";
        //文件保存路径
        String UpPath = Path+"/";
        //文件初始名
        String FileRrgName;
        //输出流
        BufferedOutputStream stream = null;

        File path = new File(UpPath);

        JSONObject jsonObject = new JSONObject();



        //如果文件夹不存在就创建一个
        if(!path.exists()){
            path.mkdir();
        }

        //filenameList
        List<String> list = new ArrayList<String>();
        for (String filenam : filemap.keySet()){
            list.add(filenam);
        }


        if(!filemap.isEmpty()) {
            for (int i = 0; i < filemap.size(); i++) {

                upfile = filemap.getFirst(list.get(i));
                System.out.println(upfile.getName());
                if (!upfile.isEmpty()) {
                    FileRrgName = upfile.getOriginalFilename();
                    if (FileRrgName.lastIndexOf(".") >= 0) {
                        Exname = FileRrgName.substring(FileRrgName.lastIndexOf("."));
                    }
                    File file = null;

                    file = new File(UpPath + FileRrgName);
                    System.out.println(UpPath + FileRrgName);
                    try {

                        byte[] bytes = upfile.getBytes();

                        stream = new BufferedOutputStream(new FileOutputStream(file));

                        stream.write(bytes);

                        stream.close();

                        jsonObject.put(list.get(i),UpPath + FileRrgName);

                    } catch (Exception e) {
                        stream = null;
                        jsonObject.put(FileRrgName,"上传失败");
                        return jsonObject;
                    }

                }
            }
        }
        return jsonObject;
    }

}
